<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 商品关注业务逻辑
 */
class ProductFollow extends LogicBase
{
    /**
     * 获取商品关注数据搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 商品ID搜索
        !empty($data['product_id']) && $where['product_id'] = $data['product_id'];
        
        // 分类搜索
        !empty($data['category']) && $where['category'] = $data['category'];
        
        // 状态搜索（是否有效关注）
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        // 搜索条件：商品名称
        !empty($data['search_data']) && $where['product_name'] = ['like', '%' . $data['search_data'] . '%'];
        
        // 时间范围搜索
        !empty($data['start_time']) && $where['create_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['create_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日数据筛选
        if (!empty($data['create_time']) && is_string($data['create_time'])) {
            $date = $data['create_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['create_time'] = ['between', [$startTime, $endTime]];
        }
        
        return $where;
    }

    /**
     * 获取用户关注商品列表
     */
    public function getUserFollowList($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $page = $data['page'] ?? 1;
        $limit = $data['limit'] ?? 20;
        $category = $data['category'] ?? '';
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        // 构建查询条件
        $where = ['user_id' => $userId];
        if (!empty($category)) {
            $where['category'] = $category;
        }
        
        // 获取关注列表
        $list = $this->modelUserFollow->getList($where, true, 'create_time desc', [
            'list_rows' => $limit,
            'page' => $page
        ]);
        
        if ($list && !empty($list)) {
            // 获取商品详细信息
            $productIds = array_column($list, 'product_id');
            $products = $this->modelProduct->getList(['id' => ['in', $productIds]], true, '', false);
            
            // 建立商品ID映射
            $productMap = [];
            foreach ($products as $product) {
                $productMap[$product['id']] = $product;
            }
            
            // 合并商品信息
            foreach ($list as $key => $item) {
                $product = $productMap[$item['product_id']] ?? null;
                if ($product) {
                    $item['product_name'] = $product['name'];
                    $item['product_image'] = $product['image'];
                    $item['current_price'] = $product['price'];
                    $item['original_price'] = $product['original_price'];
                    $item['category'] = $product['category'];
                    $item['brand'] = $product['brand'];
                    $item['specification'] = $product['specification'];
                    
                    // 计算价格变化
                    $priceChange = $product['price'] - $item['follow_price'];
                    $item['price_change'] = $priceChange;
                    $item['price_change_percent'] = $item['follow_price'] > 0 ? 
                        round(($priceChange / $item['follow_price']) * 100, 2) : 0;
                    
                    // 价格变化状态
                    if ($priceChange > 0) {
                        $item['price_status'] = 'up';
                        $item['price_status_text'] = '涨价';
                    } elseif ($priceChange < 0) {
                        $item['price_status'] = 'down';
                        $item['price_status_text'] = '降价';
                    } else {
                        $item['price_status'] = 'stable';
                        $item['price_status_text'] = '无变化';
                    }
                }
                
                // 重新赋值修改后的数据
                $list[$key] = $item;
            }
        }
        
        return [RESULT_SUCCESS, '获取关注列表成功', $list];
    }
    
    /**
     * 关注商品
     */
    public function followProduct($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $productId = $data['product_id'] ?? 0;
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        // 检查商品是否存在
        $product = $this->modelProduct->getInfo(['id' => $productId, 'product_status' => \app\common\model\Product::PRODUCT_STATUS_ONLINE]);
        if (!$product) {
            return [RESULT_ERROR, '商品不存在'];
        }
        
        // 检查是否已经关注
        $follow = $this->modelUserFollow->getInfo(['user_id' => $userId, 'product_id' => $productId]);
        if ($follow) {
            return [RESULT_ERROR, '已经关注过该商品'];
        }
        
        // 添加关注记录
        $followData = [
            'user_id' => $userId,
            'product_id' => $productId,
            'follow_price' => $product['price'],
            'category' => $product['category'],
            'create_time' => time(),
            'update_time' => time()
        ];
        
        $result = $this->modelUserFollow->insertGetId($followData);
        
        if ($result) {
            // 更新商品关注数
            $this->modelProduct->updateInfo(['id' => $productId], [
                'follow_count' => ['inc', 1],
                'update_time' => time()
            ]);
            
            return [RESULT_SUCCESS, '关注成功'];
        } else {
            return [RESULT_ERROR, '关注失败'];
        }
    }
    
    /**
     * 取消关注商品
     */
    public function unfollowProduct($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $productId = $data['product_id'] ?? 0;
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        // 检查是否已经关注
        $follow = $this->modelUserFollow->getInfo(['user_id' => $userId, 'product_id' => $productId]);
        if (!$follow) {
            return [RESULT_ERROR, '未关注该商品'];
        }
        
        // 删除关注记录
        $result = $this->modelUserFollow->deleteInfo(['user_id' => $userId, 'product_id' => $productId]);
        
        if ($result) {
            // 更新商品关注数
            $this->modelProduct->updateInfo(['id' => $productId], [
                'follow_count' => ['dec', 1],
                'update_time' => time()
            ]);
            
            // 删除相关的价格预警
            $this->modelPriceAlert->deleteInfo(['user_id' => $userId, 'product_id' => $productId]);
            
            return [RESULT_SUCCESS, '取消关注成功'];
        } else {
            return [RESULT_ERROR, '取消关注失败'];
        }
    }
    
    /**
     * 检查用户是否关注了商品
     */
    public function checkUserFollow($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $productId = $data['product_id'] ?? 0;
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        $follow = $this->modelUserFollow->getInfo(['user_id' => $userId, 'product_id' => $productId]);
        $isFollowed = !empty($follow);
        
        return [RESULT_SUCCESS, '检查关注状态成功', [
            'is_followed' => $isFollowed,
            'follow_info' => $follow ?: null
        ]];
    }
    
    /**
     * 批量检查用户关注状态
     */
    public function batchCheckUserFollow($userId, $productIds)
    {
        if (empty($productIds)) {
            return [];
        }
        
        $follows = $this->modelUserFollow->getList([
            'user_id' => $userId,
            'product_id' => ['in', $productIds]
        ], 'product_id', '', false);
        
        $followMap = [];
        foreach ($follows as $follow) {
            $followMap[$follow['product_id']] = true;
        }
        
        return $followMap;
    }
    
    /**
     * 获取关注统计信息
     */
    public function getFollowStats($userId)
    {
        $totalCount = $this->modelUserFollow->stat(['user_id' => $userId], 'count');
        
        // 按分类统计
        $categoryStats = $this->modelUserFollow->getList([
            'user_id' => $userId
        ], 'category, count(*) as count', '', false, [], 'category');
        
        return [
            'total_count' => $totalCount,
            'category_stats' => $categoryStats
        ];
    }
}